package com.dhy;

import com.dhy.handle.FileHandler;
import com.dhy.socket.DistributedClientSocket;
import com.dhy.socket.DistributedServerSocket;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author 大忽悠
 * @create 2022/7/5 10:01
 */
@Slf4j
public class Main {
    private static final Scanner input = new Scanner(System.in);
    private static DistributedServerSocket serverSocket;
    private static DistributedClientSocket clientSocket;
    //C:\\Users\\zdh\\Desktop\\tpc介绍\\part.tbl
    //C:\\Users\\zdh\\Desktop\\tpc介绍\\lineitem.tbl

    /**
     * 一个主实例和三个副本实例
     */
    public static void main(String[] args) throws FileNotFoundException, InterruptedException {
        //log.info("请输入part.tbl文件的路径和lineitem.tbl文件路径");
        saveAndCheckFile();
        log.info("输入1,启动一个主实例; 输入2,启动一个副实例;");
        try {
            chose();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void saveAndCheckFile() throws FileNotFoundException {
        //String partTbl = input.nextLine();
        File partTblFile = new File("C:\\Users\\zdh\\Desktop\\tpc介绍\\part.tbl");
        if(!partTblFile.exists()){
            throw new FileNotFoundException();
        }
        FileHandler.setPartTblFile(partTblFile);

        //String lineItemTbl = input.nextLine();
        File ineItemTblFile = new File("C:\\Users\\zdh\\Desktop\\tpc介绍\\lineitem.tbl");
        if(!ineItemTblFile.exists()){
            throw new FileNotFoundException();
        }
        FileHandler.setLineitemTblFile(ineItemTblFile);
    }


    private static void chose() throws InterruptedException {
        switch (input.nextInt()) {
            case 1: {
                log.info("启动一个主实例");
                serverSocket=new DistributedServerSocket();
                serverSocket.start();
                break;
            }
            case 2: {
                log.info("启动一个副实例");
                clientSocket=new DistributedClientSocket();
                clientSocket.start();
                break;
            }
            default: {
                log.error("输入范围有误!");
            }
        }
    }
}
